package com.atguigu.gmall.realtime.utils;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * Author: Felix
 * Date: 2022/3/20
 * Desc: 日期转换的工具类
 * 注意：如果使用simpleDateFormat对日期进行格式化，存在线程安全的问题
 * 可以使用JDK1.8之后的新日期类进行替换
 *      LocalDateTime ====> Date
 *      Instant       ====> Calendar
 *      DateTimeFormatter => SimpleDateFormat
 */
public class DateTimeUtil {
    //private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss");

    //将日期对象转换为字符串日期
    public static String toYmdhms(Date date){
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        return dtf.format(localDateTime);
    }

    //将字符串类型日期转换为时间毫秒数
    public static Long toTs(String dateStr){
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr, dtf);
        Instant instant = localDateTime.toInstant(ZoneOffset.of("+8"));
        return instant.toEpochMilli();
    }

    public static void main(String[] args) {
        System.out.println(ZoneId.systemDefault());
    }
}
